<template>
	<e-popup :show="show" @close="$emit('close')" round="32rpx">
		<view class="popup-box">
			<image class="close-btn img-40" :src="$staticPath('classify/close.png')" @tap.stop="$emit('close')"></image>
			<view class="sku-goods e-flex">
				<view class="e-m-r-30">
					<load-image mode="aspectFill" :size="['176rpx']" radius="10rpx"
						:src="checkInfo?.skuCoverImg || goodsImg">

					</load-image>
				</view>
				<view>
					<slot name="price">
						<view class="price c-red fw-600">{{$unitEn}}{{ checkInfo?.price || info.price }}</view>
					</slot>
					<view class="stock c-80" v-show="checkInfo?.stock">
						{{ $t('classify.剩余') }} {{ checkInfo?.stock }}{{ $t('classify.件') }}
					</view>
				</view>
			</view>
			<scroll-view scroll-y>
				<view class="sku-big-box" :style="{ '--backgroundColor': activeBackgroundColor }">
					<view class="sku-item-box" v-for="(item, index) in info.productSkus" :key="item.id">
						<view class="tlt">{{ item.name }}</view>

						<view class="item-box e-flex e-flex-wrap">
							<view class="item" :class="{ 'item-act': sitem.isCheck }"
								v-for="(sitem, sindex) in item.productSkuValues" :key="sitem.id"
								@tap="checkSku(index, sindex)">
								{{ sitem.name }}
							</view>
						</view>
					</view>
				</view>
			</scroll-view>
			<view class="sum-box e-flex e-flex-between">
				<view class="tlt">
					<text class="e-m-r-10">{{ $t('classify.请选择数量') }}</text>
					<text class="e-font-24 c-80" v-if="maxNumber">
						({{$t('classify.限购')+ maxNumber +$t('classify.件')}})</text>
				</view>
				<view class="sum-item e-flex">
					<image class="img-32 e-m-r-12" :src="$staticPath('classify/sub.png')" @tap="sub"></image>
					<view class="number text-center">{{ goodsNum }}</view>
					<image class="img-32 e-m-l-12" :src="$staticPath('classify/add.png')" @tap="add"></image>
				</view>
			</view>
			<view class="m-t-114">
				<e-button size="large" type="primary" shape="circle" :text="$t('common.确定')" @click="confirm"
					:throttleTime="1000"></e-button>
			</view>
			<view style="height: 20rpx;"></view>
		</view>
	</e-popup>
</template>

<script lang="ts" setup>
	import { computed, watch,nextTick } from 'vue'
	import type { GoodsSkuSpecificationItem } from '@/common/request/api'
	import type { GoodsInfo,GoodsSkuInfo } from '../type'
	import {
		useCurrentInstance
	} from '@/common/hooks'
	import {arrayDeepClone} from '@/common/utils'

	const props = defineProps<{
		checkInfo : GoodsSkuSpecificationItem,
		info : GoodsSkuInfo,
		show : boolean,
		primary : string,
		goodsNum : number,
		maxNumber : number,
		defaultSkuId : string
	}>()

	const emit = defineEmits(['close','update:goodsNum','update:checkInfo','update:info','confirm'])
	
	const ctx = useCurrentInstance()

	const goodsImg = computed(() => {
		return props.info.imgUrls ? props.info.imgUrls.split(',')[0] : ''
	})

	const activeBackgroundColor = computed(() => {
		return props.primary.replace('1)', '0.05)')
	})



	const sub = () => {
		let goodsNum = props.goodsNum;
		if (props.goodsNum <= 1) return
		goodsNum--
		emit('update:goodsNum', goodsNum)
	}
	const add = () => {
		if (Object.keys(props.checkInfo).length) {
			if (!props.maxNumber || props.goodsNum < props.maxNumber) {
				if (props.goodsNum < props.checkInfo.stock) {
					let goodsNum = props.goodsNum+1
					emit('update:goodsNum', goodsNum)
				} else {
					ctx.$toastApp(ctx.$t('classify.商品库存不足'))
				}
			} else {
				ctx.$toastApp(ctx.$t('classify.数量超出范围'))
			}
		} else {
			ctx.$toastApp(ctx.$t('classify.请选择商品规格'))
		}
	}
	
	const confirm = () => {
		if (props.checkInfo.stock == 0) {
			ctx.$toastApp(ctx.$t('classify.商品库存不足'))
			return
		}
		emit('confirm',props.goodsNum)
	}

	const checkList:Array<number|undefined> = []
	
	const checkSkuInfo = (productSkus) => {
		productSkus.map((item, i) => {
			item.productSkuValues.map(sitem => {
				if (sitem.isCheck) {
					checkList[i] = sitem.id
				}
			})
		})
		// 选择的sku与商品的productSkus长度相同，则代表商品的每个规格都有选中
		if (checkList.length == productSkus.length && !checkList.includes(
			undefined)) {
				const checkInfo = props.info.productSkuSpecifications.find(item => item.skuKey == checkList.join('/'))
				emit('update:checkInfo', checkInfo)
				emit('update:skuId', checkInfo?.id)
				emit('updateActivityData')
		}

	}
	
	const checkSku = (index:number, sindex:number) => {
		isResetCheckList = false
		let productSkus = arrayDeepClone(props.info.productSkus)
		productSkus[index].productSkuValues.map((item, indexs) => {
			item.isCheck = false
		})
		productSkus[index].productSkuValues[sindex].isCheck = true
		emit('update:info', {
			...props.info,
			productSkus
		})
		checkSkuInfo(productSkus)
		
		
	}
	let isResetCheckList = true
	
	watch(() => props.info, (newValue) => {
	
		if (newValue.productSkus.length) {
			if (isResetCheckList) {
	
				let productSkus = arrayDeepClone(props.info.productSkus)
				productSkus.forEach(item => {
					item.productSkuValues.map((items) => {
						items.isCheck = false
					})
				})
				if (props.defaultSkuId) {
					let skuInfo = newValue.productSkuSpecifications.find(item => item.id === props.defaultSkuId)
					skuInfo?.skuKey?.split('/').forEach((skuId, index) => {
						let skuIndex = productSkus[index].productSkuValues.findIndex(items =>
							`${items.id}` === skuId)
						if (skuIndex > -1) {
							productSkus[index].productSkuValues[skuIndex].isCheck = true
	
						}
					})
				} else {
					productSkus.forEach((item) => {
						item.productSkuValues[0].isCheck = true
					})
				}
				isResetCheckList = false
				emit('update:info', {
					...newValue,
					productSkus
				})
				checkSkuInfo(productSkus)
			} else {
				isResetCheckList = true
			}
	
		}
	
	})

</script>

<style lang="scss" scoped>
	.m-t-114 {
		margin-top: 114rpx !important;
	}

	.c-80 {
		color: #808080;
	}

	.popup-box {
		padding: 52rpx 32rpx 0 32rpx;
		// #ifdef APP
		padding-bottom:50px;
		// #endif

		.sku-goods {
			padding-bottom: 20rpx;

			.price {
				@include fontH(48, 58);
			}

			.stock {
				@include fontH(28, 40);
			}
		}

		scroll-view {
			max-height: 570rpx;
		}

		.sku-big-box {
			.sku-item-box {
				margin-top: 64rpx;

				.tlt {
					color: #424242;
					@include fontH(30, 42);
				}

				.item-box {
					// @include flex(start, center, wrap);

					.item {
						height: 56rpx;
						min-width: 120rpx;
						padding: 0 30rpx;
						// color: $color;
						font-size: 28rpx;
						line-height: 52rpx;
						margin-top: 20rpx;
						margin-right: 20rpx;
						text-align: center;
						background: #ededed;
						border-radius: 10rpx;
						border: 2rpx solid #ededed;

						input {
							height: 56rpx;
							width: 120rpx;
							border-radius: 8rpx;
							// color: $color;
							font-size: 28rpx;
							line-height: 56rpx;
						}
					}

					.item-act {
						color: var(--color-primary);
						background: var(--backgroundColor);
						border-color: var(--color-primary);
					}
				}
			}
		}

		.sum-box {
			margin-top: 50rpx;

			.tlt {
				color: #424242;
				@include fontH(30, 42);
			}

			.sum-item {
				font-size: 30rpx;

				.number {
					width: 84rpx;
					height: 44rpx;
					line-height: 44rpx;
					background: #f2f2f2;
					border-radius: 4px;
				}
			}
		}

		.close-btn {
			position: absolute;
			top: 40rpx;
			right: 32rpx;
		}
	}
</style>